package com.common.config;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.common.util.XsslHttpServletRequestWrapper;
import com.common.vo.LoginUser;


/**
 * 过滤配置器
 * @author YYQ
 *
 */
@WebFilter(urlPatterns = "/*",filterName = "myFilterConfig")
public class MyFilterConfig implements Filter{
	
	private final Logger logger = Logger.getLogger(MyFilterConfig.class);
	public String encoding = null;
	
	@Override
	public void destroy() {
		logger.info("销毁过滤器");
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		// 编码设置
		if(encoding != null){
			req.setCharacterEncoding(encoding);
            res.setContentType("text/html;charset="+encoding);
        }
		// 请求头
		HttpServletRequest request = (HttpServletRequest)req;
		// 响应头
		HttpServletResponse response = (HttpServletResponse)res;
		// 防止XSS漏洞
		XsslHttpServletRequestWrapper xssRequest = new XsslHttpServletRequestWrapper(request);
		// 获取会话
		HttpSession session = request.getSession();
		String url = request.getRequestURI();
		// 不过滤的请求
		if(url.indexOf("/guest") != -1
				|| url.indexOf("/data") != -1
				|| url.indexOf("/webSocket") != -1
				|| url.indexOf("/api-docs") != -1
				|| url.indexOf("/swagger") != -1
			|| url.indexOf("/views/app") != -1) {
			chain.doFilter(xssRequest,response);
			return;
		}
		String s [] = url.split("/"); 
		if(s.length > 0 && s[s.length-1].indexOf(".") == -1) {
			if(s != null && s.length > 0){
				logger.info("正在过滤路径："+request.getServletPath());
				LoginUser user =(LoginUser) session.getAttribute("loginUser");
				if(user != null){ 
					if(s[s.length-1].equals("login") || s[s.length-1].equals("SB-Layui")){// 登录成功过直接跳回主界面
						request.getRequestDispatcher("/jumpMain").forward(request, response);
						return ;
					}
					chain.doFilter(xssRequest,response);//交给下个过滤器
					return;
				}else{
					if((s[s.length-1].equals("loginJudge") && request.getParameter("userName") != null)){// 登录校验请求
						chain.doFilter(xssRequest,response);
						return;
					}
				}
			}
		}else {
			chain.doFilter(xssRequest,response);
			return;
		}
		request.getRequestDispatcher("/login").forward(request, response);// 直接跳转登录界面
	}
	
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		logger.info("初始化过滤器");
		encoding = arg0.getInitParameter("encoding");// 编码格式UTF-8 web.xml配置
	}


	
}
